<template>
  <div class="container">
    <div class="left-panel">
      <h3>证件照片</h3>
      <div class="id-photo-container">
        <div class="photo-upload" @click="triggerUpload('portrait')">
          <img v-if="'http://localhost:9095/'+form.portraitUrl" :src="form.portraitUrl_preview" class="id-photo" />
          <div v-else class="upload-placeholder">
            <i class="el-icon-plus"></i>
            <p>上传人像面</p>
          </div>
          <input
              type="file"
              ref="portraitUpload"
              @change="(e) => handleFileChange('portrait', e)"
              accept="image/*"
              style="display: none"
          />
        </div>
        <div class="photo-upload" @click="triggerUpload('nationalEmblem')">
          <img v-if="form.nationalEmblemUrl" :src="form.nationalEmblemUrlPreview" class="id-photo" />
          <div v-else class="upload-placeholder">
            <i class="el-icon-plus"></i>
            <p>上传国徽面</p>
          </div>
          <input
              type="file"
              ref="nationalEmblemUpload"
              @change="(e) => handleFileChange('nationalEmblem', e)"
              accept="image/*"
              style="display: none"
          />
        </div>
      </div>

      <div class="info-wrapper">
        <div class="info-container">
          <el-form :model="form" label-position="right" label-width="100px">
            <el-form-item label="证件姓名">
              <el-input v-model="form.name" placeholder="请输入真实姓名"></el-input>
            </el-form-item>

            <el-form-item label="证件号码">
              <el-input v-model="form.idNumber" placeholder="请输入身份证号码"></el-input>
            </el-form-item>

            <el-form-item label="认证状态">
              <el-tag :type="statusTagType">
                {{ verificationStatusText }}
              </el-tag>
              <span v-if="verificationStatus === 'PENDING'" class="status-hint">预计审核时间: 30分钟</span>
            </el-form-item>
          </el-form>

          <div class="id-requirements">
            <p><span class="info-label">身份证照片要求:</span></p>
            <p class="grey-text">请持本人有效二代身份证；</p>
            <p>
              <span class="grey-text">拍摄时确保身份证</span>
              <span class="highlight">边框完整，字体清晰，亮度均匀；</span>
            </p>
          </div>

          <div class="example-photos">
            <div v-for="(example, index) in examples" :key="index" class="example-photo">
              <div class="image-container">
                <img :src="example.image" :class="{ 'good-example': example.good }" />
              </div>
              <span :class="{ 'good-label': example.good }">{{ example.label }}</span>
            </div>
          </div>
        </div>
      </div>

      <el-button
          type="primary"
          class="confirm-button"
          :loading="submitting"
          @click="handleSubmit"
      >
        {{ verificationStatus === 'APPROVED' ? '重新认证' : '提交认证' }}
      </el-button>
    </div>

    <div class="right-panel">
      <div class="user-info">
        <img :src="userAvatar" class="user-avatar" />
        <div class="user-name">
          {{ userName }}
          <el-tag size="mini" :type="verificationStatusTagType">
            {{ verificationStatusLabel }}
          </el-tag>
        </div>
      </div>
      <div class="button-container">
        <el-button type="primary" class="action-button" @click="goToResume">我的简历</el-button>
        <el-button class="action-button" @click="goToJobs">我的招聘</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
// import { getToken } from '@/utils/auth';


export default {
  data() {
    return {
      form: {
        name: '',
        idNumber: '',
        portraitUrl: '',
        nationalEmblemUrl: '',
        nationalEmblemUrlPreview: '',
        portraitUrl_preview: '',
      },
      verificationStatus: 'UNVERIFIED', // UNVERIFIED 未实名, PENDING 审核中, APPROVED 已实名(通过), REJECTED 审核被拒绝
      verificationStatusText: '未实名',
      submitting: false,
      examples: [
        { image: 'imgs/good-example.png', good: true, label: '标准' },
        { image: 'imgs/bad-example1.png', good: false, label: '边框缺失' },
        { image: 'imgs/bad-example2.png', good: false, label: '照片模糊' },
        { image: 'imgs/bad-example3.png', good: false, label: '闪光强烈' }
      ],
      userAvatar: 'imgs/default-avatar.png',
      userName: '未登录用户'
    }
  },
  computed: {
    verificationStatusLabel() {
      const map = {
        UNVERIFIED: '未实名',
        PENDING: '审核中',
        APPROVED: '已实名',
        REJECTED: '已拒绝'
      };
      return map[this.verificationStatus] || '未知状态';
    },
    verificationStatusTagType() {
      const map = {
        UNVERIFIED: 'danger',
        PENDING: 'warning',
        APPROVED: 'success',
        REJECTED: 'danger'
      };
      return map[this.verificationStatus] || 'info';
    },
    statusTagType() {
      return this.verificationStatus === 'APPROVED' ? 'success' :
          this.verificationStatus === 'REJECTED' ? 'danger' :
              'info';
    },
    statusHint() {
      return this.verificationStatus === 'PENDING' ? '预计审核时间: 30分钟' : '';
    }
  },
  created() {
    this.checkLoginStatus();
    this.loadVerificationStatus();
  },
  methods: {
    async checkLoginStatus() {
      function getToken() {
        // 假设 token 存储在 localStorage 中
        return localStorage.getItem('Authorization_user');
        //localStorage.setItem('Authorization', 'your_token_here');
        //localStorage.removeItem('Authorization');
      }

      try {
        const token = getToken();
        /*if (!token) {////////////////////////////////////////////////////////////////////////////////
          this.$message.warning('请先登录');
          this.$router.push('/login');
          return;
        }*/

        // 获取当前用户信息
        /*const userRes = await axios.get(BASE_URL+'/api/user/info');//////////////////////////////////////
        this.userName = userRes.data.name || '未设置姓名';
        this.userAvatar = userRes.data.avatar || 'imgs/default-avatar.png';*/
      } catch (error) {
        console.error('检查登录状态失败:', error);
        //alert(error+"检查登录状态失败:");
      }
    },





    async loadVerificationStatus() {
      //try {
        //const res = await axios.get(BASE_URL+'api/verification/getCurrentUserVerification');
        const res = await axios.get('http://localhost:9095/api/verification/getCurrentUserVerification');
        const data = res.data;
        alert("data.statusText::"+data.statusText);
        if (data.statusText === '0') {
          this.verificationStatus = 'UNVERIFIED';
          this.verificationStatusText = '正在审核';
        } else if (data.statusText === '1') {
          this.verificationStatus = 'APPROVED';
          this.verificationStatusText = '已认证';
          //alert("show pass"+(BASE_URL+data.nationalEmblemUrl));
          // 回显已认证信息
          this.form = {
            name: data.name,
            idNumber: data.idNumber,
            portraitUrl_preview: BASE_URL+data.portraitUrl,
            portraitUrl: data.portraitUrl,
            nationalEmblemUrlPreview: BASE_URL+data.nationalEmblemUrl,
            nationalEmblemUrl: data.nationalEmblemUrl
          };
          //alert("data.statusText=1已认证::portraitUrl"+portraitUrl);
        } else if (data.statusText === '2') {
          this.verificationStatus = 'REJECTED';
          this.verificationStatusText = '认证被拒';
          // 回显被拒信息
          //alert("show reject"+(BASE_URL+data.nationalEmblemUrl));          //nationalEmble  国徽
          this.form = {
            name: data.name,
            idNumber: data.idNumber,
            portraitUrl_preview: BASE_URL+data.portraitUrl,
            portraitUrl: data.portraitUrl,
            nationalEmblemUrlPreview: BASE_URL+data.nationalEmblemUrl,
            nationalEmblemUrl: data.nationalEmblemUrl
          };
          alert("data.statusText=2拒绝::portraitUrl"+data.portraitUrl);        //portrait 头像
          this.$message.warning('您的上次认证被拒绝，请修改后重新提交');
        }
      /*} catch (error) {
        console.error('获取认证状态失败:', error);
        // 如果接口报错，默认显示未认证状态
        this.verificationStatus = 'UNVERIFIED';
        this.verificationStatusText = '未认证';
      }*/
    },

    triggerUpload(type) {
      if (type === 'portrait') {
        this.$refs.portraitUpload.click();
      } else {
        this.$refs.nationalEmblemUpload.click();
      }
    },

    async handleFileChange(type, event) {
      const file = event.target.files[0];
      if (!file) return;

      // 限制文件大小 (5MB)
      if (file.size > 5 * 1024 * 1024) {
        this.$message.error('图片大小不能超过5MB');
        return;
      }

      // 预览图片
      const reader = new FileReader();
      reader.onload = (e) => {
        if (type === 'portrait') {
          //this.form.portraitUrl = e.target.result;
          this.form.portraitUrl_preview = e.target.result;
        } else {
          this.form.nationalEmblemUrlPreview = e.target.result;
        }
      };
      reader.readAsDataURL(file);






      const formData = new FormData();
      formData.append('file', file);

//      try {
            const res = await axios.post(BASE_URL+'/v1/uploadFile/upload', formData, {
              headers: {
                'Content-Type': 'multipart/form-data'
              }
            });

            if (type === 'portrait') {//portrait 头像  人像
              //this.form.portraitUrl = res.data.url;
              this.form.portraitUrl = res.data.data.url;
              //alert("人像上传图片完成--this.form.portraitUrl::"+res.data.data.url);
            } else { //nationalEmblem 国徽
              //this.form.nationalEmblemUrl = res.data.url;
              this.form.nationalEmblemUrl = res.data.data.url;
              //alert(res.data.data.url);
              //alert("国徽上传图片完成--this.form.nationalEmblemUrl::"+res.data.data.url);
            }
   /*   } catch (error) {
        console.error('上传图片失败:', error);
        this.$message.error('图片上传失败，请重试');
      }*/







      // 创建 FormData 实例并添加文件
      /*const formData = new FormData();
      formData.append("file", file); // "file" 是后端接口接收的字段名   //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

      try {
            axios.post("/v1/uploadFile", formData, {
              headers: {
                "Content-Type": "multipart/form-data"
              }
            }).then(
                function (response) {
                    console.log(response);
                }
            );
            console.log("上传成功:", res.data);
      } catch (error) {
            console.error("上传失败:", error);    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
      }*/

















    },





    async uploadImage(file, type) {
      const formData = new FormData();
      formData.append('file', file);

      try {
        const res = await axios.post(BASE_URL+'/v1/uploadFile/upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })

       /* if (type === 'portrait') {
          this.form.portraitUrl = res.data.url;
        } else {
          this.form.nationalEmblemUrl = res.data.url;
        }*/
        console.log('上传图片成功:', res.data);
        //alert("上传图片成功:"+this.form.portraitUrl);
        console.log(this.form.portraitUrl );
        console.log(this.form.nationalEmblemUrl );
      } catch (error) {
        console.error('上传图片失败:', error);
        this.$message.error('图片上传失败，请重试');
      }
    },





    async handleSubmit() {
      if (!this.form.name || !this.form.idNumber || !this.form.portraitUrl || !this.form.nationalEmblemUrl) {
        this.$message.warning('请填写完整信息并上传身份证照片');
        return;
      }

      if (!this.validateIdNumber(this.form.idNumber)) {
        this.$message.warning('请输入有效的身份证号码');
        return;
      }

      this.submitting = true;

      try {
        console.log("this.form.nationalEmblemUrl:"+this.form.nationalEmblemUrl);
        console.log("this.form.portraitUrl::"+this.form.portraitUrl);
        alert("this.verificationStatus::"+this.verificationStatus);
        const res = await axios.post(BASE_URL+'/api/verification/postForm/'+this.verificationStatus, this.form);
        alert("res.data.data.id::"+res.data.data.id);
        if (res.data.data.id  || res.data.data ) {
          this.$message.success('认证信息提交成功，请等待审核');
          this.verificationStatus = 'PENDING';
          this.verificationStatusText = '审核中';
        }
        this.$router.push('/verifyPassed');

      } catch (error) {
        console.error('提交认证失败:', error);
        this.$message.error('提交认证失败，请重试');
      } finally {
        this.submitting = false;
      }
    },








    validateIdNumber(idNumber) {
      // 简单的身份证号码验证
      const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
      return reg.test(idNumber);
    },




    goToResume() {
      this.$router.push('/resume');
    },










    goToJobs() {
      this.$router.push('/jobs');
    },



  }
}
</script>

<style scoped>
.container {
  display: flex;
  justify-content: center;
  align-items: flex-start;
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.left-panel {
  background: linear-gradient(to bottom, #f0f0f0 50%, white 50%);
  background-size: 100% 50%;
  background-repeat: no-repeat;
  background-color: white;
  padding: 20px;
  border-radius: 4px;
  width: 60%;
  margin-right: 20px;
  text-align: center;
}

.info-wrapper {
  display: flex;
  justify-content: center;
}

.info-container {
  display: inline-block;
  text-align: left;
  width: 40%;
}

.id-photo-container {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-bottom: 20px;
}

.photo-upload {
  width: 200px;
  height: 130px;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.photo-upload:hover {
  border-color: #409EFF;
}

.upload-placeholder {
  color: #909399;
}

.upload-placeholder i {
  font-size: 24px;
  margin-bottom: 5px;
}

.id-photo {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.info-item {
  margin-bottom: 20px;
}

.id-requirements {
  margin-top: 20px;
  text-align: left;
}

.grey-text {
  color: #909399;
}

.highlight {
  color: #f56c6c;
}

.example-photos {
  background-color: #fff;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
  margin-top: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  position: relative;
  display: flex;
  flex-wrap: nowrap;
  overflow-x: auto;
  gap: 15px;
  justify-content: center;
}

.example-photos::before {
  content: "拍照示例";
  position: absolute;
  top: -10px;
  left: 50%;
  transform: translateX(-50%);
  background-color: #fff;
  color: #909399;
  font-size: 12px;
  padding: 0 5px;
  border: 1px solid #ebeef5;
  border-radius: 2px;
}

.example-photo {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 20%;
  min-width: 100px;
}

.image-container {
  width: 80px;
  height: 50px;
  overflow: hidden;
  margin-bottom: 5px;
}

.example-photo img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.good-example {
  border: 2px solid #67c23a !important;
}

.good-label {
  color: #67c23a;
}

.confirm-button {
  width: 40%;
  margin-top: 20px;
}

.right-panel {
  background-color: white;
  padding: 20px;
  border-radius: 4px;
  width: 15%;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.user-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
}

.user-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  margin-bottom: 10px;
}

.user-name {
  font-size: 18px;
  font-weight: bold;
}

.button-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
  width: 100%;
}

.action-button {
  width: 100%;
  margin-bottom: 10px;
}

.status-hint {
  margin-left: 10px;
  color: #909399;
  font-size: 12px;
}
</style>